package com.example.yilanchatserver.business.freechat;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class OpenAiWebClient {
    private WebClient webClient;


    @Value("${chatgpt.stream}")
    private String CHAT_API;

    /**
     * dev采用代理访问
     */
    @PostConstruct
    public void init() {
        initProd();
    }



    public void initProd() {
        log.info("initProd");
        this.webClient = WebClient.builder()
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .build();
    }


    public Flux<String> getChatResponse(String model, List<Map<String, String>> prompt, Integer maxTokens, Double temperature, Double topP) {
        JSONObject params = new JSONObject();

//        params.put("model", "gpt-3.5-turbo");
//        params.put("max_tokens", maxTokens);
//        params.put("stream", true);
//        params.put("temperature", temperature);
//        params.put("top_p", topP);
//        params.put("user", user);
//        JSONObject message = new JSONObject();
//        message.put("role", "user");
//        message.put("content", prompt);
        params.put("model", model);
        List<Map<String, String>> qaPairs = new ArrayList<>();

        for(int i = 0;i < prompt.size();i++){

            Map<String, String> tmp =  prompt.get(i);
            tmp.put("role", tmp.remove("talker"));
            tmp.put("content", tmp.remove("text"));
            qaPairs.add(tmp);
        }
        params.put("qaPairs", qaPairs);

        return webClient.post()
                .uri(CHAT_API)
                .bodyValue(params.toJSONString())
                .retrieve()
                .bodyToFlux(String.class)
                .onErrorResume(WebClientResponseException.class, ex -> {
                    HttpStatus status = ex.getStatusCode();
                    String res = ex.getResponseBodyAsString();
                    log.error("OpenAI API error: {} {}", status, res);
                    return Mono.error(new RuntimeException(res));
                });

    }
}
